package com.letao.rest.service.impl;

import com.letao.common.pojo.LetaoResult;
import com.letao.common.utils.JsonUtils;
import com.letao.mapper.TbContentMapper;
import com.letao.pojo.TbContent;
import com.letao.pojo.TbContentExample;
import com.letao.rest.dao.JedisClient;
import com.letao.rest.service.ContentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by ac on 2017/1/18.
 */
@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private TbContentMapper contentMapper;

    @Autowired
    private JedisClient jedisClient;

    @Value("${REDIS_CONTENT_KEY}")
    private String REDIS_CONTENT_KEY;

    @Override
    public LetaoResult getContentList(Long categoryId) {
        try {
            String hget = jedisClient.hget(REDIS_CONTENT_KEY, categoryId + "");
            if(!StringUtils.isBlank(hget)){
                List<TbContent> list = JsonUtils.jsonToList(hget, TbContent.class);
                return LetaoResult.ok(list);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        TbContentExample example = new TbContentExample();
        example.createCriteria().andCategoryIdEqualTo(categoryId);
        List<TbContent> list = contentMapper.selectByExample(example);

        try {
            jedisClient.hset(REDIS_CONTENT_KEY, categoryId + "", JsonUtils.objectToJson(list) );

        }catch (Exception e){
            e.printStackTrace();
        }

        return LetaoResult.ok(list);
    }
}
